﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Security.Principal;
using System.Threading;
using EntModApp.EntServices.Presentation;

namespace EntModApp.EntServices.PresentationLogic
{
  public class GenericApplicationState : 
    SyncNotifyObject, 
    IApplicationState
  {
    private bool setThreadCulture;
    private bool setThreadPrincipal;

    public static readonly IPrincipal UnauthenticatedUser =
      new GenericPrincipal(new GenericIdentity(""), new string[0]);

    public GenericApplicationState()
      : this(true, true)
    {
    }

    public GenericApplicationState(bool setThreadCulture, bool setThreadPrincipal)
    {
      Session = new Dictionary<string, object>();
      this.setThreadCulture = setThreadCulture;
      this.setThreadPrincipal = setThreadPrincipal;
    }

    private CultureInfo _Culture;
    public CultureInfo Culture
    {
      get
      {
        if (_Culture != null)
          return _Culture;
        if (setThreadCulture)
          return Thread.CurrentThread.CurrentUICulture ?? CultureInfo.InstalledUICulture;
        return CultureInfo.InstalledUICulture;
      }
      set
      {
        _Culture = value ?? CultureInfo.InstalledUICulture;
        if (setThreadCulture)
          Thread.CurrentThread.CurrentUICulture = _Culture;
        OnPropertyChanged(() => Culture);
      }
    }

    protected IPrincipal _User;
    public IPrincipal User
    {
      get
      {
        if (_User != null)
          return _User;
        if (setThreadPrincipal)
          return Thread.CurrentPrincipal ?? UnauthenticatedUser;
        return UnauthenticatedUser;
      }
      private set
      {
        _User = value ?? UnauthenticatedUser;
        if (setThreadPrincipal)
          Thread.CurrentPrincipal = _User;
        OnPropertyChanged(() => User);
      }
    }

    public bool Login(IPrincipal user)
    {
      if (user == null)
      {
        Logout();
        return false;
      }
      User = user;
      return user.Identity.IsAuthenticated;
    }

    public void Logout()
    {
      User = new GenericPrincipal(new GenericIdentity(""), new string[0]);
    }

    public IDictionary<string, object> Session { get; private set; }


    private DeviceSpecs currentDevice;
    public DeviceSpecs CurrentDevice
    {
      get
      {
        return currentDevice;
      }
      set
      {
        if (currentDevice == value) return;
        currentDevice = value;
        OnPropertyChanged(() => CurrentDevice);
      }
    }
  }
}
